package com.caption.core.utils;
import com.alibaba.fastjson.JSON;
import com.caption.core.constants.SecurityConstant;
import com.caption.core.exception.ServiceException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

/**
 * @description: TODO
 * @author: 码农
 * @date: 2022-01-01 20:14:36
 */
public class JwtUtils {
    private JwtUtils() {
    }

    public static String createToken(Long userId, String secret, String content, Integer expire) {
        // 登陆成功生成JWT
        String token = Jwts.builder()
                // 放入用户名和用户ID
                .setId(userId + "")
                // 主题
                .setSubject(userId+"")
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("mall")
                // 自定义属性
                .claim(SecurityConstant.TOKEN_CONTENT, content)
                // 失效时间
                .setExpiration(new Date(System.currentTimeMillis() + expire * 60 * 1000))
                // 签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        token = SecurityConstant.TOKEN_PREFIX + token;
        return token;
    }


    public static Claims parseToken(String token, String secret) {
        // 解析token
        Claims claims = null;
        try {
            String replace = token.replace(SecurityConstant.TOKEN_PREFIX, "");
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(replace).getBody();
        } catch (ExpiredJwtException e) {
            throw new ServiceException("token过期,请重新登录");
        } catch (Exception e) {
            throw new ServiceException("解析token错误,请重新登录");
        }
        return claims;
    }

    public static void main(String[] args) {
        String token = createToken(1L, "123456", "{'name':'zhangsan'}", 60);
        System.out.println(token);
        Claims claims = parseToken(token, "123456");
        Object userInfo = claims.get("userInfo");
        System.out.println(userInfo);
        System.out.println(JSON.toJSONString(claims));
    }


}
